package com.neusoft.databus.agent.pool.wangguan;

import java.io.IOException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool2.PooledObject;
import org.springframework.stereotype.Component;

import com.neusoft.databus.common.connection.WangguanConnection;
import com.neusoft.databus.common.exception.RetryableException;
import com.neusoft.databus.common.pool.AbstractPoolFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * description
 *
 * @author sunchf
 * @date 2019年4月2日 上午9:28:26
 */
@Slf4j
@Component
public class WangguanFactory extends AbstractPoolFactory<WangguanConnection, FTPClient> {

    @Override
    public FTPClient create(final WangguanConnection wangguanConnection) throws Exception {

        final FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(1000 * 30);//设置连接超时时间
        ftpClient.setControlEncoding("utf-8");//设置ftp字符集
        ftpClient.enterLocalPassiveMode();//设置被动模式，文件传输端口设置
        try {
            ftpClient.connect(wangguanConnection.getHost(), wangguanConnection.getPort());
            ftpClient.login(wangguanConnection.getLoginName(), wangguanConnection.getLoginPass());
            final int replyCode = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(replyCode)) {
                WangguanFactory.log.error("connect ftp {} failed", wangguanConnection.getHost());
                ftpClient.disconnect();
                throw new RetryableException("连接失败");
            }
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//设置文件传输模式为二进制，可以保证传输的内容不会被改变
            WangguanFactory.log.info("replyCode==========={}", replyCode);
        } catch (final IOException e) {
            WangguanFactory.log.error("connect fail ------->>>", e);
            throw new RetryableException("连接失败");
        }
        return ftpClient;
    }

    @Override
    public void destroy(FTPClient v) {
        try {
            v.disconnect();
        } catch (final Exception e) {
        }
        v = null;
    }

    @Override
    public boolean validateObject(final WangguanConnection key, final PooledObject<FTPClient> p) {
        return p.getObject().isConnected() && p.getObject().isAvailable();
    }

}
